package com.ambitor.grass.sql.statement;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Types;

import com.ambitor.grass.sql.data.ColumnObject;
import com.ambitor.grass.sql.data.Parameter;

public class ParameterStatementImpl implements IStatement {

	private PreparedStatement statement;
	private String sql;

	public ParameterStatementImpl(Connection conn, String sql) throws Exception {
		this.sql = sql;
		// this.statement = conn.prepareStatement(this.sql);
		this.statement = conn.prepareStatement(this.sql,
				Statement.RETURN_GENERATED_KEYS);
	}

	public void close() throws Exception {
		this.statement.close();
	}

	public PreparedStatement getStatement() throws Exception {
		return this.statement;
	}

	protected void setParameters(Parameter param) throws Exception {
		for (int i = 0; i < param.size(); i++) {
			if (param.get(i) == null) {
				statement.setNull(i + 1, Types.VARCHAR);
			} else {
				Object value = param.get(i);
				if (value instanceof ColumnObject) {
					ColumnObject columnObject = (ColumnObject) value;
					if (columnObject.getType() == Types.LONGVARCHAR) {
						statement.setCharacterStream(i + 1, new StringReader(
								columnObject.getValue().toString()),
								columnObject.getValue().toString().length());
					}
				} else {
					statement.setObject(i + 1, value);
				}
			}
		}
	}
}
